/*
 * StartApplication.java
 *
 * Created on October 8, 2006, 12:15 AM
 */

package org.sunspotworld;

import com.sun.spot.core.resources.Resources;
import com.sun.spot.core.resources.transducers.ITriColorLED;
import com.sun.spot.core.util.Utils;
import com.sun.spot.edemo.EDemoBoard;
import com.sun.spot.espot.service.BootloaderListenerService;
import com.sun.spot.ieee_802_15_4_radio.IRadioPolicyManager;
import com.sun.spot.ieee_802_15_4_radio.util.IEEEAddress;
import com.sun.spot.multihop.io.j2me.radiogram.Radiogram;
import com.sun.spot.multihop.io.j2me.radiogram.RadiogramConnection;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

/**
 * The startApp method of this class is called by the VM to start the
 * application.
 * 
 * The manifest specifies this class as MIDlet-1, which means it will
 * be selected for execution.
 */
public class StartApplication extends MIDlet {
    private IRadioPolicyManager rpm = (IRadioPolicyManager)Resources.lookup(IRadioPolicyManager.class);
    private IEEEAddress ourAddr = new IEEEAddress(rpm.getIEEEAddress());
    private IEEEAddress toAddress = new IEEEAddress(ourAddr.asDottedHex().substring(0,15) + "4121");    //set to last 4 digits of detector SPOT Address

    private Thread listenThread = new Thread() {
        public void run() {
            RadiogramConnection beacConn = null;
            Radiogram brg;
            try {
                beacConn = (RadiogramConnection) Connector.open("radiogram://:46");
                brg = (Radiogram)beacConn.newDatagram(beacConn.getMaximumLength());
                while (true) {
                    brg.reset();
                    beacConn.receive(brg);
                    toAddress = new IEEEAddress(brg.getAddress());
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    };

    protected void startApp() throws MIDletStateChangeException {
        System.out.println("Hello, world");
        BootloaderListenerService.getInstance().start();   // monitor the USB (if connected) and recognize commands from host
        RadiogramConnection conn = null;
        rpm.setOutputPower(31);  //set power to maximum (this is the default, but written here for completeness).  Both my packets and relayed packets will go far
        System.out.println("Our radio address = " + ourAddr.asDottedHex());
        
        ITriColorLED [] leds = EDemoBoard.getInstance().getLEDs();
        leds[0].setRGB(100,0,0);                // set color to moderate red
        listenThread.start();
        while (true) {
            try {
                conn = (RadiogramConnection)Connector.open("radiogram://:45");
                conn.setMaxBroadcastHops(0);
                Radiogram rg = (Radiogram)conn.newDatagram(conn.getMaximumLength());
                while (true) {
                    try {
                        leds[0].setOn();                    // Blink LED
                        Utils.sleep(250);                   // wait 1/4 seconds
                        leds[0].setOff();
                        rg.reset();
                        rg.setAddress(toAddress.asDottedHex());
                        rg.writeLong(toAddress.asLong());  //write toAddress into beginning of Radiogram
                        rg.writeBoolean(false);  //write false : this is not from the low-power source
                        //these messages show that the relay is working and sending messages correctly to the detector, even when the sender is out of range or off
                        conn.send(rg);
                        Utils.sleep(1000);//*/
                    } catch (IOException iOException) {
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
            Utils.sleep(3000);                  // wait 3 seconds
        }
    }

    protected void pauseApp() {
        // This will never be called by the Squawk VM
    }

    protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
        // Only called if startApp throws any exception other than MIDletStateChangeException
    }
}
